package com.j2eefast.bussiness.contract.service;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.j2eefast.bussiness.contract.entity.BusClassifyEntity;
import com.j2eefast.bussiness.contract.entity.BusInstallsEntity;
import com.j2eefast.bussiness.contract.mapper.BusClassifyMapper;
import com.j2eefast.bussiness.contract.mapper.BusInstallsMapper;
import com.j2eefast.common.core.base.entity.Ztree;
import com.j2eefast.common.core.exception.RxcException;
import com.j2eefast.common.core.page.Query;
import com.j2eefast.common.core.utils.MapUtil;
import com.j2eefast.common.core.utils.PageUtil;
import com.j2eefast.common.core.utils.SpringUtil;
import com.j2eefast.common.core.utils.ToolUtil;
import com.j2eefast.framework.annotation.DataFilter;
import com.j2eefast.framework.sys.entity.SysCompEntity;
import com.j2eefast.framework.sys.entity.SysUserEntity;
import com.j2eefast.framework.utils.Constant;
import com.j2eefast.framework.utils.UserUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.util.*;


/**
 * <p>设备分类</p>
 *
 * @author: summer
 * @date: 2021-06-01 10:41
 * @web: http://www.letukeji.cn
 * @version: 1.0.1
 */

@Service
public class BusClassifyService extends ServiceImpl<BusClassifyMapper, BusClassifyEntity> {

    @Resource
    protected BusClassifyMapper busClassifyMapper;

    public List<BusClassifyEntity> findList(Map<String, Object> params) {
        return SpringUtil.getAopProxy(this).getDeptList(params);
    }
    @DataFilter(compAlias="c",deptAlias = "c")
    public List<BusClassifyEntity> getDeptList(Map<String, Object> params){
        String className = (String)params.get("className");
        String parentId =(String)params.get("parentId");

        return this.baseMapper.getDeptList(
//                StrUtil.nullToDefault(className,""),
//                StrUtil.nullToDefault(parentId,""),
                (String) params.get(Constant.SQL_FILTER));
    }
    public BusClassifyEntity findCompById(Long id) {
        return busClassifyMapper.findCompById(id);
    }
    /**
     * 查询公司树
     * @return
     */
    public List<Ztree> findCompTree( Long parentId) {
        Map<String,Object> mapp = new HashMap<>();
        mapp.put("parentId",parentId);
        List<BusClassifyEntity> list = SpringUtil.getAopProxy(this).getDeptList(mapp);
        List<Ztree> ztrees = initZtree(list);
        return ztrees;
    }
    public List<Ztree> initZtree(List<BusClassifyEntity> list) {
        return  initZtree(list,null);
    }
    public List<Ztree> initZtree(List<BusClassifyEntity> compList, List<String> roleCompList){

        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = !ToolUtil.isEmpty(roleCompList);
        for (BusClassifyEntity comp : compList) {
                Ztree ztree = new Ztree();
                ztree.setId(comp.getId());
                ztree.setpId(comp.getParentId());
                ztree.setName(comp.getClassName());
                ztree.setTitle(comp.getClassName());
                ztrees.add(ztree);
        }
        return ztrees;
    }

    public void checkDataScope(Long... ids) {
//        if (!UserUtils.hasAnyRoleKeys(Constant.SU_ADMIN)) {
            //check current user has data scope for the deleted use
            Map<String, Object> params = Maps.newConcurrentMap();
            params.put("ids", ids);
            List<?> listData =SpringUtil.getAopProxy(this).getDeptList(params);
            if (null == listData || listData.size() == 0 || listData.size() != ids.length) {
                throw new RxcException(ToolUtil.message("illegal request"),"50001");
            }
//        }
    }

    public boolean checkCompNameUnique(BusClassifyEntity comp) {
        Long compId = ToolUtil.isEmpty(comp.getId()) ? -1L : comp.getId();
        BusClassifyEntity info = this.getOne(new QueryWrapper<BusClassifyEntity>().
                eq("id",comp.getId()).eq("parent_id",comp.getParentId()));
        if (ToolUtil.isNotEmpty(info) && info.getId().longValue() != compId.longValue())
        {
            return  false;
        }
        return true;
    }

    public boolean add(BusClassifyEntity comp){
        Date date = new Date();//创建一个时间对象，获取到当前的时间
        comp.setCreateTime(date);
        String userId= UserUtils.getUserInfo().getName();
        comp.setCreateBy(userId);
        if(this.save(comp)){
            return true;
        }
        return false;
    }
    public boolean update(BusClassifyEntity comp){
        if(this.updateById(comp)){
            return true;
        }
        return false;
    }
    /**
     * 通过id删除
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean delSysCompById(Long id) {

        // 先判断是否有子公司
        List<BusClassifyEntity> list = this.listByMap(new MapUtil().put("parent_id", id));
        if (ToolUtil.isNotEmpty(list)) {
            throw new RxcException("请先删除子分类","50001");
        }
        // 在判断公司是否有分配到用户上面如果改公司已经分配到用户上,先删除用户在删
        List<BusClassifyEntity> users = busClassifyMapper.listByMap(id);
        if (ToolUtil.isNotEmpty(users)) {
            throw new RxcException("请先删除关联分类","50001");
        }
        //删除关联地区
     //   busClassifyMapper.removeByMap(id);

        if(this.removeById(id)){
            return true;
        }else{
            return false;
        }
    }





    /**
     * 页面展示查询翻页
     */
    public PageUtil findPage(Map<String, Object> params) {
//		String sampleCode = (String) params.get("sampleCode");
		//String type = (String) params.get("type");


        Page<BusClassifyEntity> page = busClassifyMapper.findPage(
                new Query<BusClassifyEntity>(params).getPage(),
				//StrUtil.nullToDefault(type,""),
//				StrUtil.nullToDefault(sampleType,""),
                (String) params.get(Constant.SQL_FILTER));
        return new PageUtil(page);
    }

    public List<BusClassifyEntity> getInstallsList(){
        return busClassifyMapper.getInstallsList();
    }

    public boolean deleteByIds(Long[] ids) {

        return busClassifyMapper.deleteByIds(ids);

    }

    public boolean updateCheck(Long id) {
        Long userId= UserUtils.getUserInfo().getId();

        return busClassifyMapper.updateCheck(id ,userId);

    }
    public SysUserEntity getSysById(@Param("userId")Long userId){
        return busClassifyMapper.getSysById(userId);
    }


    public List<BusClassifyEntity> getPriceList(Long id){
        return busClassifyMapper.getPriceList(id);
    }



}
